#include "IndirectionDrie.h"
#include "IndirectionTwee.h"
#include <cassert>
#include <iostream>

IndirectionDrie::IndirectionDrie(FileSystem* filesystem, byte *bytes) : Indirection(filesystem, bytes) {
	int j = 0;
    for (int i = 0; i < INDSIZ; ++i) {
	    blocklist[i] = getlong(bytes, j);
	    j += 4;
    }
}

IndirectionDrie::~IndirectionDrie() {
}

long IndirectionDrie::getBlocknummer(int relative_block_position) {
    int offset = relative_block_position % (INDSIZ * INDSIZ);
    assert(offset >= 0);
    assert(offset <= INDSIZ * INDSIZ);

    int position_indirection2 = (relative_block_position - offset) / (INDSIZ * INDSIZ);
    assert(position_indirection2 >= 0);
    assert(position_indirection2 <= INDSIZ);

    long address_indirection2 = blocklist[position_indirection2];

    if (address_indirection2 == 0) return -1;

    Blok* indirection2_block = filesystem->getBlok(address_indirection2);

	byte* bytes_temp = indirection2_block->getBytes();
	byte bytes[DBLKSIZ];
	for (int i = 0; i < DBLKSIZ; ++i) {
		bytes[i] = bytes_temp[i];
	}

	IndirectionTwee* indirection2 = new IndirectionTwee(filesystem, bytes); // TODO delete instantie van object

    long blocknummer = indirection2->getBlocknummer(offset);

    delete indirection2;
    indirection2 = 0;

    return blocknummer;
}
